<template>
  <div class="wrap">
    <Search
      :address="address"
      :lat="lat"
      :lng="lng"
      @updateLatLng="updateLatLng"
    ></Search>
    <div id="container"></div>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, watch } from 'vue'
import { get } from '@/utils/request'
import Search from '../components/Search'
export default {
  name: 'Home',
  components: {
    Search
  },
  setup() {
    let map = null
    let center = null
    let marker = null
    let editor = null
    let info = null
    let addressInfo = reactive({
      lat: '',
      lng: '',
      address: ''
    })
    //监听器
    watch(
      () => addressInfo.lat,
      (curlat, prevCount) => {
        const { lat, lng } = { ...addressInfo }
        updateCenter(lat, lng)
        updateMarker(lat, lng)
      }
    )
    onMounted(() => {
      getCurrenLocation()
    })
    //初始化地图
    const initMap = (obj) => {
      const { lat, lng } = { ...obj }
      center = new TMap.LatLng(lat || 39.98412, lng || 116.307484)
      map = new TMap.Map(document.getElementById('container'), {
        center: center,
        zoom: 17.2,
        pitch: 43.5,
        rotation: 45
      })
      // 创建信息窗
      info = new TMap.InfoWindow({
        map,
        position: map.getCenter()
      }).close()
      //注册点击事件
      map.on('click', (e) => {
        const { lat, lng } = { ...e.latLng }
        addressInfo.lat = lat
        addressInfo.lng = lng
        geocoder(lat, lng)
        // 获取click事件返回的poi信息
        let poi = e.poi
        if (poi) {
          // 拾取到POI
          info
            .setContent(poi.name)
            .setPosition(poi.latLng)
            .open()
        } else {
          // 没有拾取到POI
          info.close()
        }
      })
      //初始化marker
      marker = new TMap.MultiMarker({
        id: 'marker', //图层id
        map: map,
        styles: {
          //点标注的相关样式
          marker: new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 16, y: 32 },
            highlight: new TMap.MarkerStyle({
              src:
                'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker-pink.png'
            })
          })
        },
        geometries: [
          {
            //点标注数据数组
            id: 'marker1',
            styleId: 'marker',
            position: new TMap.LatLng(lat, lng),
            properties: {
              title: 'marker'
            }
          }
        ]
      })
    }
    //更新中心点坐标
    const updateCenter = (lat, lng) => {
      map.setCenter(new TMap.LatLng(lat, lng))
    }
    //更新marker标记位置
    const updateMarker = (lat, lng) => {
      marker.updateGeometries([
        {
          styleId: 'marker',
          id: 'marker1',
          position: new TMap.LatLng(lat, lng)
        }
      ])
    }
    //获取当前位置
    const getCurrenLocation = () => {
      var geolocation = new qq.maps.Geolocation()
      geolocation.getLocation(
        (e) => {
          let { lat, lng } = { ...e }
          addressInfo.lat = lat
          addressInfo.lng = lng
          initMap({ lat, lng })
          geocoder(lat, lng)
        },
        (err) => {
          console.log(err)
          addressInfo.lat = 0
          addressInfo.lng = 0
          initMap({ lat: '', lng: '' })
        }
      )
    }
    //逆地址解析
    const geocoder = async (lat, lng) => {
      // let res = await get('/ws/geocoder/v1', {
      //   location: `${lat},${lng}`
      // })
      // addressInfo.address = res.result.address
      var data = {
        location: `${lat},${lng}`,
        key: 'VYKBZ-AAF3U-NHBVL-BKPFE-MTOIO-EDBDH',
        get_poi: 1
      }
      data.output = 'jsonp'
      $.ajax({
        type: 'get',
        url: `https://apis.map.qq.com/ws/geocoder/v1`,
        dataType: 'jsonp',
        data: data,
        jsonp: 'callback',
        jsonpCallback: 'QQmap',
        success: (res) => {
          console.log(res, 'res')
          if (res.status == '0') {
            addressInfo.address = res.result.address
          }
        },
        error: function(errors) {
          // console.log(errors);
        }
      })
    }
    //修改lat,lng
    const updateLatLng = (obj) => {
      addressInfo.lat = obj.lat
      addressInfo.lng = obj.lng
      addressInfo.address = obj.address
    }

    return {
      ...toRefs(addressInfo),
      geocoder,
      updateLatLng
    }
  }
}
</script>

<style scoped lang="less">
.wrap {
  width: 100vw;
  height: 100vh;
  position: relative;
  overflow: hidden;
}
#container {
  width: 100vw;
  height: 100vh;
}
</style>
